package net.wzw.localcache;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import org.springframework.cache.caffeine.CaffeineCache;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static cn.hutool.core.annotation.AnnotationUtil.setValue;

/**
 * @author wzw
 * @date 2025/5/3
 * @Description CaffineCache 本地缓存
 */
public class CaffineCache {

    public static void main(String[] args) throws  InterruptedException{

        Cache<Integer,String> cache =
                Caffeine.newBuilder()
                        .initialCapacity(10)
                        .maximumSize(100) //设置缓存最大哦那个量为100 超过100 点之后会按照LRU最近最少使用算法来移除缓存
                        .expireAfterWrite(8, TimeUnit.SECONDS)
                        .recordStats()//设置要缓存的命中率
                        .removalListener((Integer key,String value, RemovalCause cause) ->
                                {
                                 //打印日志
                                    System.out.println("key:"+key + "value :" + value + "数据已过期");


                                }
                                ).build(key -> setValue(1).apply(1));

                                Integer key = 2;

                                cache.put(2,"wzw测试");
                                //循环打印
                        for (int i = 0 ; i<20; i++){

                            //获取缓存
                           // cache.getIfPresent(1)
                           String str =  cache.get(key,CaffineCache::getValueFromDB);
                           //挨个打印
                            System.out.println(str);
                            //休眠一秒
                            TimeUnit.SECONDS.sleep(1);
                            if (i == 10) {

                                System.out.println("--------------");
                                //调用主动删除，将某个key的缓存直接删除
                                cache.invalidate(1);
                                System.out.println("--------");

                            }

                        }
                        //将某个key的缓存直接删除，会调用removalListener
                        cache.invalidate(1);
                        //将一批Key的缓存直接删除，会调用removalListener
                         cache.invalidateAll(new ArrayList<>());
                         // 删除所有缓存数据
                         cache.invalidateAll();
                         //打印缓存命中率情况
        System.out.println("cache stats:"+ cache.stats().toString());
    }
        public static Function<Integer,String > setValue(Integer key) {


               return t ->key + "value";

        }

        private static String getValueFromDB(Integer key) {

            return "v";
        }


}
